#include "pawn.h"
#include "src/move.h"
#include "src/constants.h"

Pawn::Pawn( int x, int y, QString pixmap_path, int color, QGraphicsItem* parent ) : BoardFigure( x, y, pixmap_path, color, parent )
{
}

QList<Move*>& Pawn::getPossibleMoves( BoardFigure* board[8][8] ) {
  qDebug() << "Pawn GetPossibleMoves called";

  if ( possibleMovesReady ) return possibleMoves;

  clearPossibleMoves();
  int dx = 0, dy = 0;
  int dxLeftEating = 0, dyLeftEating = 0;
  int dxRightEating = 0, dyRightEating = 0;

  bool isFirstMove = 0;

  if ( getColor() == Constants::COLOR_BLACK ) {
    dy = -1;
    isFirstMove = ( getBoardY() == Constants::BOARD_SIZE - 2);

    dxLeftEating  =  1;
    dyLeftEating  = -1;
    dxRightEating = -1;
    dyRightEating = -1; 
    
  }
  else {
    dy = 1;
    isFirstMove = ( getBoardY() == 1);
    dxLeftEating  = -1;
    dyLeftEating  =  1;
    dxRightEating =  1;
    dyRightEating =  1; 
  }

  int newX, newY;

  // simple move one step forward
  newX = getBoardX()+dx;
  newY = getBoardY()+dy;
  if (
      checkNewPos( newX, newY )
      && board[newX][newY] == 0
     ) {
    Move* move = new Move(getBoardX(), getBoardY(), newX, newY );
    possibleMoves.push_back( move );
  }

  // first move two step forward
  if (isFirstMove ) {
    newX = getBoardX();
    newY = getBoardY()+2*dy;

    if ( 
        checkNewPos( newX, newY )
        && board[newX][newY] == 0
        && board[newX][newY - dy] == 0
       ) {
      Move* move = new Move(getBoardX(), getBoardY(), newX , newY );
      possibleMoves.push_back( move );
    }
  }

  // simple capturing
  newX = getBoardX() + dxLeftEating;
  newY = getBoardY() + dyLeftEating;
  QPoint* attackField1 = new QPoint( newX, newY );
  attackedFields.push_back( attackField1 );

  if (
      checkNewPos( newX, newY )
      && board[newX][newY]
      && board[newX][newY]->getColor() != getColor()
     ) {
      Move* move = new Move(getBoardX(), getBoardY(), newX , newY );
      possibleMoves.push_back( move );
  }

  newX = getBoardX() + dxRightEating;
  newY = getBoardY() + dyRightEating;
  QPoint* attackField2 = new QPoint( newX, newY );
  attackedFields.push_back( attackField2 );

  if (
      checkNewPos( newX, newY )
      && board[newX][newY]
      && board[newX][newY]->getColor() != getColor()
     ) {
      Move* move = new Move(getBoardX(), getBoardY(), newX , newY );
      possibleMoves.push_back( move );
  }
  
  //
  // TODO: enpassant capturing
  //
  
  possibleMovesReady = true;
  attackedFieldsReady = true;
  return possibleMoves;
}

QList<QPoint*>& Pawn::getAttackedFields( BoardFigure* board[8][8] )
{
  QList<Move*> moves;
  if ( attackedFieldsReady ) return attackedFields;
  else moves = getPossibleMoves( board );
  
  return attackedFields;
}

